package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class HttpClient {
    private Socket socket;
    private String serverIp;
    private int port;

    public HttpClient(String serverIp, int port) throws IOException {
        socket = new Socket(serverIp, port);
        this.serverIp = serverIp;
        this.port = port;
    }

    public String get(String url){
        // 按照 http 协议构造 http 请求报文
        StringBuilder request = new StringBuilder();
        // 首行
        request.append("GET " + url + " HTTP/1.1\n");
        // 请求头
        request.append("Host: " + serverIp + ":" + port + "\n");
        // 空行
        request.append("\n");

        String response = null;
        try(OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream()){
            // 发送 http 请求
            outputStream.write(request.toString().getBytes());
            // 接收 http 响应
            byte[] buffer = new byte[1024 * 1024];
            int n = inputStream.read(buffer);
            response = new String( buffer, 0, n, "utf-8");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return response;
    }

    public String post(String url, String body){
        // 按照 http 协议构造 http 请求报文
        StringBuilder request = new StringBuilder();
        // 首行
        request.append("POST " + url + " HTTP/1.1\n");
        // 请求头
        request.append("Host: " + serverIp + ":" + port + "\n");
        request.append("Content-Length: " + body.getBytes().length + "\n");
        request.append("Content-Type: txt/plain\n");
        // 空行
        request.append("\n");
        // 正文
        request.append(body);

        String response = null;
        try(OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream()){
            outputStream.write(request.toString().getBytes());
            // 接收 http 响应
            byte[] buffer = new byte[1024 * 1024];
            int n = inputStream.read(buffer);
            response = new String(buffer, 0, n, "utf-8");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return response;
    }

    public static void main(String[] args) throws IOException {
        // 测试数据
//        HttpClient httpClient = new HttpClient("42.192.83.143", 8080);
//        String getResp = httpClient.get("AjaxMockServer/info");
//        System.out.println(getResp);
//        String body = "this is body";
//        String postResp = httpClient.post("AjaxMockServer/info", body);
//        System.out.println(postResp);

        HttpClient httpClient = new HttpClient("www.sogou.com", 80);
        String getResp = httpClient.get("/index.html");
        System.out.println(getResp);
    }
}
